package com.sskj.cndragon.ui.activity;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.gamerole.orcameralib.MaskView;
import com.google.gson.Gson;
import com.sskj.cndragon.R;
import com.sskj.cndragon.bean.JsonCityBean;
import com.sskj.cndragon.presenter.AddAddressActivityPresenter;
import com.sskj.cndragon.view.ToolBarLayout;
import com.sskj.common.base.App;
import com.sskj.common.util.CheckUtil;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.GSonUtil;
import com.sskj.common.util.KeyBoardUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseActivity;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


public class AddAddressActivity extends BaseActivity<AddAddressActivityPresenter> {
    @BindView(R.id.toolbar)
    ToolBarLayout toolbar;
    @BindView(R.id.et_name_shouhuoren)
    EditText etNameShouhuoren;
    @BindView(R.id.et_mobile_shouhuoren)
    EditText etMobileShouhuoren;
    @BindView(R.id.tv0)
    TextView tv0;
    @BindView(R.id.tv_choose)
    TextView tvChoose;
    @BindView(R.id.et_detail_address)
    EditText etDetailAddress;


    private List<JsonCityBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private static boolean isLoaded = false;

    private String province;//省
    private String city;//市
    private String area;//区/县
    private String type;//类型：1 添加 2 修改
    private String addressId = "";


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

//                        Toast.makeText(AddAddressActivity.this, "Begin Parse Data", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
//                    Toast.makeText(AddAddressActivity.this, "Parse Succeed", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
//                    Toast.makeText(AddAddressActivity.this, "Parse Failed", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_add_address;
    }

    @Override
    public AddAddressActivityPresenter getPresenter() {
        return new AddAddressActivityPresenter();
    }

    @Override
    protected void initView() {
        super.initView();
        type = getIntent().getStringExtra(Constans.ADR_TYPE);
        if (type.equals("2")) {
            addressId = getIntent().getStringExtra(Constans.ADR_ID);
            etNameShouhuoren.setText(getIntent().getStringExtra(Constans.ADR_NAME));
            etMobileShouhuoren.setText(getIntent().getStringExtra(Constans.ADR_TEL));
            etDetailAddress.setText(getIntent().getStringExtra(Constans.ADR_DETAIL));
            province = getIntent().getStringExtra(Constans.ADR_PROVICE);
            city = getIntent().getStringExtra(Constans.ADR_CITY);
            area = getIntent().getStringExtra(Constans.ADR_AREA);
            tv0.setText(province + " " + city + " " + area);
            toolbar.setTitle(App.INSTANCE.getString(R.string.appBianjishouhuodizhi));
        } else if (type.equals("1")) {
            toolbar.setTitle(App.INSTANCE.getString(R.string.tianjiaxindizhi));
        }

        toolbar.setLeftButtonOnClickListener(view -> finish());
        toolbar.setRightButtonOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isEmpty(etNameShouhuoren)) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.appQingshurushouhuorenxingming));
                    return;
                }
                if (isEmpty(etMobileShouhuoren)) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.appQingshurushouhuorenshoujihao));
                    return;
                }
                if (!CheckUtil.isMobile(getEtext(etMobileShouhuoren))) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.appQingshuruzhengquedeshoujihao));
                    return;
                }
                if (isEmpty(province) || isEmpty(city) || isEmpty(area)) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.appQingxuanzeshengshiqu));
                    return;
                }
                if (isEmpty(etDetailAddress)) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.appQingshuruxiangxidizhi));
                    return;
                }
                mPresenter.addOrEditAddress(SPUtil.get(SPConfig.ID, ""),
                        getEtext(etNameShouhuoren),
                        getEtext(etMobileShouhuoren),
                        province, city, area, getEtext(etDetailAddress),
                        type, addressId);
            }
        });
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);

        ClickUtil.click(300, tvChoose, new ClickUtil.Click() {
            @Override
            public void click() {
                KeyBoardUtil.hideSoftKeyboard(AddAddressActivity.this);
                if (isLoaded) {
                    showPickerView();
                } else {
                    Toast.makeText(AddAddressActivity.this, "城市列表加载中...", Toast.LENGTH_SHORT).show();
                }

            }
        });


    }

    private void showPickerView() {// 弹出选择器
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                province = options1Items.size() > 0 ?
                        options1Items.get(options1).getPickerViewText() : "";

                city = options2Items.size() > 0
                        && options2Items.get(options1).size() > 0 ?
                        options2Items.get(options1).get(options2) : "";

                area = options2Items.size() > 0
                        && options3Items.get(options1).size() > 0
                        && options3Items.get(options1).get(options2).size() > 0 ?
                        options3Items.get(options1).get(options2).get(options3) : "";
                String tx = province + " " + city + " " + area;
                tv0.setText(tx);
            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GSonUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonCityBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String cityName = jsonBean.get(i).getCityList().get(c).getName();
                cityList.add(cityName);//添加城市
                ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                /*if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    city_AreaList.add("");
                } else {
                    city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }*/
                city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                province_AreaList.add(city_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(cityList);

            /**
             * 添加地区数据
             */
            options3Items.add(province_AreaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    public ArrayList<JsonCityBean> parseData(String result) {//Gson 解析
        ArrayList<JsonCityBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonCityBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonCityBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    public static void start(Context context, String type) {
        Intent intent = new Intent(context, AddAddressActivity.class);
        intent.putExtra(Constans.ADR_TYPE, type);
        context.startActivity(intent);
    }

    public static void start(Context context, String type, String name, String mobile, String province, String city, String area, String detail, String addressId) {
        Intent intent = new Intent(context, AddAddressActivity.class);
        intent.putExtra(Constans.ADR_TYPE, type);
        intent.putExtra(Constans.ADR_NAME, name);
        intent.putExtra(Constans.ADR_TEL, mobile);
        intent.putExtra(Constans.ADR_PROVICE, province);
        intent.putExtra(Constans.ADR_CITY, city);
        intent.putExtra(Constans.ADR_AREA, area);
        intent.putExtra(Constans.ADR_DETAIL, detail);
        intent.putExtra(Constans.ADR_ID, addressId);
        context.startActivity(intent);
    }

    public void addressSuccess() {
        finish();
    }
}
